

export function createWebSocketConnection() {
    if('WebSocket' in window){
        // const ws = 'ws://' + newHost + '/ws'
        // console.log('准备连接：', ws);
        // connect(ws);
    }
}
let websocket = null;
export function send(msg){
    websocket && websocket.send(msg);
}

//Make a websocket connection with the server.
export  function connect(host, connectSuccess) {
    let newHost  =host.replace('http://','').replace('https://','')
    const ws = 'ws://' + newHost + '/ws'
    console.log('准备连接：', ws);
    if (!websocket) {
        websocket = new WebSocket(ws);
    }

    websocket.onopen = function() {
        console.log('ws opened');
        // chrome.storage.local.get("devHost", ({devHost})=> {
        //     websocket.send(JSON.stringify({userLoginId: data.username}));
        // })
    };

    websocket.onmessage = function (event) {
        var received_msg = JSON.parse(event.data);
        console.log('原始消息:', received_msg)
        if(received_msg){
            connectSuccess && connectSuccess(received_msg)
        }
        
        console.log(received_msg)
    };

    websocket.onclose = function() {
        websocket = undefined;
        chrome.storage.local.get(['ws_session'], function(data) {
            if (data.ws_session) {
                createWebSocketConnection();
            }
        });
    };
    websocket.onerror = function(e){
        console.log('ws error',e)
    }
}

export  function closeWebSocketConnection(username) {
    if (websocket != null || websocket != undefined) {
        websocket.close();
        websocket = undefined;
    }
}